package io.renren.admin;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.renren.entity.FileManagerEntity;
import io.renren.service.FileManagerService;
import io.renren.utils.PageUtils;
import io.renren.utils.Query;
import io.renren.utils.R;
import io.renren.utils.RRException;


/**
 * 文件管理
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-06-24 20:59:11
 */
@RestController
@RequestMapping("filemanager")
public class FileManagerController {
	
	@Autowired
	private FileManagerService fileManagerService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("filemanager:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);

		List<FileManagerEntity> fileManagerList = fileManagerService.queryList(query);
		int total = fileManagerService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(fileManagerList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("filemanager:info")
	public R info(@PathVariable("id") Integer id){
		FileManagerEntity fileManager = fileManagerService.queryObject(id);
		
		return R.ok().put("fileManager", fileManager);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("filemanager:save")
	public R save(@RequestBody FileManagerEntity fileManager){
		fileManagerService.save(fileManager);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("filemanager:update")
	public R update(@RequestBody FileManagerEntity fileManager){
		fileManagerService.update(fileManager);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("filemanager:delete")
	public R delete(@RequestBody Integer[] ids){
		fileManagerService.deleteBatch(ids);
		
		return R.ok();
	}
	
	@RequestMapping("/upload")
	@RequiresPermissions("filemanager:upload")
	public R upload(@RequestParam("file") MultipartFile file, FileManagerEntity fileManager) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		fileManagerService.upload(file, fileManager);
		
		return R.ok();
	}
}
